package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/hashicorp/consul/api"
)

func Register(address string, port int, name string, tags []string, id string) error {
	// consul配置初始化
	cfg := api.DefaultConfig()
	cfg.Address = address + ":8500"
	// 创建client，用于注册服务
	client, err := api.NewClient(cfg)
	if err != nil {
		return err
	}
	// 生成注册对象
	registration := new(api.AgentServiceRegistration)
	// 用该方式也可以
	/*
		registration := api.AgentServiceRegistration{
			Name: name,
			Address: address,
		}
	*/
	registration.Name = name
	registration.ID = id
	registration.Port = port
	registration.Tags = tags
	registration.Address = address
	// 生成对应的检查对象 健康检测
	check := &api.AgentServiceCheck{
		HTTP:                           fmt.Sprintf("http://%s:%d", address, port),
		Timeout:                        "5s",  // 超时时间
		Interval:                       "5s",  // 间隔5s检测一次
		DeregisterCriticalServiceAfter: "10s", // 检测失败后注销服务
	}
	registration.Check = check
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		return err
	}
	return nil
}

// 获取所有服务
func AllService() error {
	// consul配置初始化
	cfg := api.DefaultConfig()
	cfg.Address = "127.0.0.1:8500"
	// 创建client，用于注册服务
	client, err := api.NewClient(cfg)
	if err != nil {
		return err
	}

	data, err := client.Agent().Services()
	if err != nil {
		return err
	}
	for k, _ := range data {
		fmt.Println(k)
	}
	return nil
}

//
func FilterService(serviceName string) error {
	// consul配置初始化
	cfg := api.DefaultConfig()
	cfg.Address = "127.0.0.1:8500"
	// 创建client，用于注册服务
	client, err := api.NewClient(cfg)
	if err != nil {
		return err
	}
	data, _, err := client.Agent().Service(serviceName, nil)
	if err != nil {
		return err
	}
	fmt.Println(data.Address)
	fmt.Println(data.Service)
	return nil
}

func main() {
	err := Register("localhost", 8021, "user-web", []string{"mxshop", "boby"}, "user-web")
	if err != nil {
		panic(err.Error())
	}
	// AllService()
	FilterService("user-web")
	fmt.Println("服务开启")

	r := gin.Default()
	// consul健康检查回调函数
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "ok",
		})
	})
	r.Run(":8021")
}
